package logs

import (
	"fmt"
	"log"
	"os"
	"time"
)

var (
	File     *os.File
	Filepath = "./logs/"
	Logger   = &log.Logger{}
)

func init() {
	createDir()
	createFile()
	Logger = log.New(File, "", log.LstdFlags)
	go monitor()
}
func Info(v ...any) {
	Logger.Print("[info]", fmt.Sprintln(v...))
}
func Success(v ...any) {
	Logger.Print("[success]", fmt.Sprintln(v...))
}
func Error(v ...any) {
	Logger.Print("[error]", fmt.Sprintln(v...))
}
func Warning(v ...any) {
	Logger.Print("[warning]", fmt.Sprintln(v...))
}
func Sql(v ...any) {
	Logger.Print("[sql]", fmt.Sprintln(v...))
}
func Test(v ...any) {
	Logger.Print("[test]", fmt.Sprintln(v...))
}
func Write(v ...any) {
	Logger.Println(v...)
}
func monitor() {
	for {
		createDir()
		_filename := Filepath + "/" + time.Now().Format("2006/01/02") + ".log"
		_, err := os.Stat(_filename)
		if err != nil {
			if os.IsNotExist(err) {
				_createFile(_filename)
				Logger.SetOutput(File)
				createFile()
			} else {
				fmt.Println("[logs.monitor]", 1, "os.Stat", err.Error())
			}
		}
		time.Sleep(time.Second)
	}
}
func createDir() {
	dir := Filepath + time.Now().Format("2006/01/")
	_, err := os.Stat(dir)
	if err != nil {
		if !os.IsNotExist(err) {
			fmt.Println("[logs.CreateDir]", 2, "os.Stat", err.Error())
			return
		}
		err = os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			fmt.Println("[logs.CreateDir]", 3, "os.MkdirAll", err.Error())
		}
	}
}
func createFile() {
	file := Filepath + time.Now().Format("2006/01/02") + ".log"
	_createFile(file)
}
func _createFile(_filename string) {
	openFile, err := os.OpenFile(_filename, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
	if err != nil {
		fmt.Println("[logs._createFile]", 4, "os.OpenFile", err.Error())
		return
	}
	File = openFile
}
